package com.tc.itfarm.service.impl;

import com.tc.itfarm.api.exception.BusinessException;
import com.tc.itfarm.api.model.SingleTableDao;
import com.tc.itfarm.api.util.DateUtils;
import com.tc.itfarm.dao.MenuDao;
import com.tc.itfarm.model.Menu;
import com.tc.itfarm.model.MenuArctile;
import com.tc.itfarm.model.MenuCriteria;
import com.tc.itfarm.service.MenuArticleService;
import com.tc.itfarm.service.MenuService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created by wangdongdong on 2016/8/29.
 */
@Service
public class MenuServiceImpl extends BaseServiceImpl<Menu> implements MenuService {

    private static final Logger logger = LoggerFactory.getLogger(MenuServiceImpl.class);

    @Resource
    private MenuDao menuDao;
    @Resource
    private MenuArticleService menuArticleService;

    @Override
    protected SingleTableDao getSingleDao() {
        return menuDao;
    }

    @Override
    public List<Menu> selectAll() {
        List<Menu> menus = super.selectAll();
        return menus;
    }

    @Override
    public void save(Menu menu, Integer [] articleIds) throws BusinessException {
        if (menu.getRecordId() == null && menu.getOrderNo() == null) {
            Integer order = menuDao.selectMaxOrder(menu.getParent());
            if (order == null) {
                menu.setOrderNo(menuDao.selectById(menu.getParent()).getOrderNo() + 1);
            } else {
                menu.setOrderNo(order + 1);
            }
        }
        if (menu.getRecordId() == null) {
            menu.setCreateTime(DateUtils.now());
            // 查询是否名称重复
            MenuCriteria criteria = new MenuCriteria();
            criteria.or().andNameEqualTo(menu.getName());
            int count = menuDao.countByCriteria(criteria);
            if (count > 0) {
                throw BusinessException.create(logger, "菜单名称已存在!");
            }
            menuDao.insert(menu);
        } else {
            menuDao.updateByIdSelective(menu);
        }
        // 插入菜单关联文章
        menuArticleService.updateArticleIds(menu.getRecordId(), articleIds);
    }

    @Override
    public Integer selectMaxOrder(Integer parentId) {
        return menuDao.selectMaxOrder(parentId);
    }
}
